<template>
  <basic-container>
    <div class="table">
      <!-- 表单列表 -->
      <avue-crud
        ref="crud"
        :data="data"
        :option="option"
        :page.sync="page"
        @on-load="getOrderList"
        @size-change="sizeChange"
        @expand-change="expandChange"
        @refresh-change="refreshChange"
        @current-change="currentChange"
        @search-change="searchChange"
        @selection-change="handleSelectionChange"
      >
        <!-- 操作栏 -->
        <template slot="menu" slot-scope="scope">
          <el-col>
            <div class="detailText">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-upload"
                @click="printTable(scope.row)"
              >打印</el-button>
              <el-button
                type="text"
                icon="el-icon-success"
                size="small "
                @click="confirm(scope.row)"
              >确认</el-button>
              <el-button type="text" icon="el-icon-error" size="small " @click="supplyCancel">取消</el-button>
              <el-button
                v-show="scope.row.status == 5"
                type="text"
                icon="el-icon-home"
                size="small "
                @click="supplyShip(scope.row)"
              >发货</el-button>
              <el-dropdown>
                <el-button type="text" icon="el-icon-release" size="small " @click="afterSale">售后</el-button>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item>退换货</el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
            </div>
          </el-col>
        </template>

        <template slot-scope="scope" slot="menuLeft">
          <el-button type="primary" @click="printSelectOrder">批量打印</el-button>
          <el-button type="primary" @click="printAgain">重新打印</el-button>
        </template>

        <!-- 展开行数据内容 -->
        <template slot="expand" slot-scope="{row}">
          <div>
            <div v-for="(item,index) in supplyorderList " :key="index ">
              <el-row :span="24" class="search-wrap" v-if="item.supplySn==row.supplySn">
                <el-col :span="6">
                  <div class="detailDiv">
                    <div>
                      <el-image style="width: 60px; height: 60px" :src="item.goodsImg"></el-image>
                    </div>
                    <div class="detailText">
                      <p>商品名称:{{item.goodsName}}</p>
                      <span>商品规格:{{item.modelName}}</span>
                    </div>
                  </div>
                </el-col>
                <el-col :span="3">
                  <div class="detailText">
                    <p @click="purchaseSerial(item)">
                      采购订单编号:
                      <br />
                      <span style="color:#409EFF">{{item.buyOrderSns}}</span>
                    </p>
                  </div>
                </el-col>
                <el-col :span="3">
                  <div class="detailText">
                    <p @click="shipSerial(item)">
                      发货单编号:
                      <br />
                      <span style="color:#409EFF">{{item.shipRecordSn}}</span>
                    </p>
                  </div>
                </el-col>
                <el-col :span="3">
                  <div class="detailText">
                    <p>
                      金额:
                      {{item.amount}}
                    </p>
                  </div>
                </el-col>
                <el-col :span="3">
                  <div class="detailText">
                    <p>成交价格:{{item.dealPrice}}</p>
                  </div>
                </el-col>
                <el-col :span="2">
                  <div class="detailText">
                    <p>
                      采购数量:
                      {{item.goodsNum}}
                    </p>
                  </div>
                </el-col>
                <el-col :span="2">
                  <div class="detailText">
                    <p>单位:{{item.unit}}</p>
                  </div>
                </el-col>
                <el-col :span="2">
                  <div class="detailText">
                    <p>状态:{{item.payStatus==0?'未付':item.payStatus==1?'已付':'部分支付'}}</p>
                  </div>
                </el-col>
              </el-row>
            </div>
          </div>
        </template>
      </avue-crud>
      <!-- 弹出框 -->
      <el-dialog title="供应订单打印" :visible.sync="dialogPrint" width="90%">
        <v-print ref="printOrderTable" :value="checkedItem" :concise-list="detailList"></v-print>
      </el-dialog>
    </div>
  </basic-container>
</template>
<script>
import {
  orderList,
  detailsList,
  supplyConfirm,
  supplyInfo,
  fetchInfoByOrderSn
} from "../../api/supply/order_list";
// 打印页面
import vPrint from "./components/print";
// 表格标题
import { tableOption } from "../../const/crud/supply/order_list";
export default {
  components: {
    vPrint
  },
  data() {
    return {
      input: "",
      serchForm: {},
      supplyInfo,

      supplyorderList: [],
      goodsImg: "",
      activeNames: ["1"],
      option: tableOption,

      page: {
        total: 0, // 总页数
        currentPage: 1, // 当前页数
        pageSize: 20, // 每页显示多少条,
        isAsc: false // 是否倒序
      },
      data: [],
      // 选中的数据
      choseData: [],
      // 打印
      multipleSelection: [],
      headHtmlPrint: "",
      bodyHtmlPrint: "",
      checkedItem: {},
      dialogPrint: false,
      detailList: []
    };
  },
  created() {
    this.option = JSON.parse(JSON.stringify(tableOption));
  },
  mounted() {
    this.getHeight();
  },
  methods: {
    // 从新打印
    printAgain() {
      if (this.headHtmlPrint && this.bodyHtmlPrint) {
        this.printBatch(this.headHtmlPrint, this.bodyHtmlPrint);
      } else {
        this.$message.warning("没有可重新打印的采购单");
      }
    },
    // 批量打印
    printSelectOrder() {
      let selectOrderList = this.multipleSelection;
      // console.log(selectOrderList);
      if (selectOrderList.length == 0) {
        this.$message.warning("未选择需打印采购单");
        return;
      }
      this.dialogPrint = true;
      this.headHtmlPrint = "";
      this.bodyHtmlPrint = "";
      this.batchPrint(
        0,
        selectOrderList,
        "",
        "",
        "",
        this.batchPrint,
        this.printBatch
      );
      // console.log(this.batchPrint());
    },
    batchPrint(
      index,
      selectArray,
      headHtml,
      selectBodyHtml,
      msg,
      callback,
      endPrint
    ) {
      this.dialogPrint = true;
      let item = selectArray[index];
      this.checkedItem = item;
      if (index == selectArray.length - 1) {
        headHtml = this.$refs.printOrderTable.printHeadHtml();
      }
      //获取商品详情
      detailsList({ supplySn: item.supplySn }).then(res => {
        this.$message.warning("采购单" + (index + 1) + "  等待数据加载");
        if (res.status == 200) {
          this.detailList = res.data.data.detailList;
          this.totalGoods = this.detailList.length;
        } else {
          this.detailList = [];
          this.totalGoods = 0;
        }
        // 等待数据加载
        let time = 10 * (this.totalGoods + 1) > time;
        time = time > 500 ? time : 500;
        let _that = this;
        setTimeout(function() {
          if (_that.detailList.length > 0) {
            let bodyHtml = _that.$refs.printOrderTable.printBodyHtml(
              "supplySn"
            );
            msg +=
              "<p>#" +
              (index + 1) +
              " 采购单 " +
              item.supplySn +
              " 商品数 " +
              _that.detailList.length +
              "</p>";
            selectBodyHtml =
              selectBodyHtml +
              bodyHtml +
              '<div style="height: 50px;page-break-after:always"></div>';
          }
          _that.dialogPrint = false;
          index++;
          if (index < selectArray.length) {
            callback(
              index,
              selectArray,
              headHtml,
              selectBodyHtml,
              msg,
              callback,
              endPrint
            );
          } else {
            _that.$notify({
              title: "打印的采购单信息:",
              dangerouslyUseHTMLString: true,
              message: msg,
              duration: 0
            });
            _that.headHtmlPrint = headHtml;
            _that.bodyHtmlPrint = selectBodyHtml;
            endPrint(headHtml, selectBodyHtml);
          }
        }, time);
      });
    },

    // 调起批量打印
    printBatch(headHtml, bodyHtml) {
      let newWindow = window.open("", "打印");
      let newHtml =
        "<html>" + headHtml + "<body>" + bodyHtml + "</body></html>";
      newWindow.document.write(newHtml);
      newWindow.document.close();
      newWindow.window.onload = function() {
        newWindow.window.print();
      };
    },
    // 单个打印按钮
    printTable(item) {
      // console.log(item);
      this.checkedItem = item;
      this.getsupplyDetails(item.supplySn);
      // this.purchaseList(item.supplySn);
      this.dialogPrint = true;
    },
    // 这儿是选中事件
    handleSelectionChange(val) {
      this.choseData = val;
      // console.log(this.choseData);
      this.multipleSelection = val;
      // console.log("selection", this.multipleSelection);
    },

    // 确认调取参数
    getsupplyConfirm(params) {
      supplyConfirm(params).then(res => {
        console.log(res);
        if (res.status === 200) {
          this.$message.success("确认成功");
        } else {
          this.$message.error("确认失败");
        }
      });
    },
    // 确认按钮
    confirm(row) {
      let params = {
        supplySn: row.supplySn,
        remarks: ""
      };
      console.log(params);
      this.getsupplyConfirm(params);
    },
    // 获取商品详情
    getsupplyDetails(supplySn) {
      let params = {
        supplySn: supplySn
      };
      //获取订单号信息
      supplyInfo(params).then(res => {

        let buyOrderSns = res.data.data.buyOrderSns;
        let shipRecordSn = res.data.data.shipRecordSn;
        //获取商品详情
        detailsList(params).then(res => {
          this.detailList = res.data.data.detailList;
          let arr = [];
          this.detailList.forEach(element => {
            element.buyOrderSns = buyOrderSns;
            element.shipRecordSn = shipRecordSn;
            arr.push(element);
          });
          this.supplyorderList = arr;
        });
      });
    },
    // 展开行，请求详情数据
    expandChange(row, expendList) {
      this.getsupplyDetails(row.supplySn);
    },
    // 接口调用
    async getOrderList(query) {
      this.page.total = 20;
      let queryWhere = {
        current: this.page.currentPage,
        size: this.page.pageSize,
        ...query
      };
      const { data: res } = await orderList(queryWhere);
      this.data = res.data.records;
      this.page.total = res.data.total;
    },
    // 行数
    sizeChange(val) {
      this.page.currentPage = 1;
      this.page.pageSize = val;
      this.getOrderList(this.page);
    },
    // 页码
    currentChange(val) {
      this.page.currentPage = val;
      this.getOrderList(this.page);
    },
    /**
     * 搜索回调
     */
    searchChange(form, done) {
      console.log(form);
      this.getOrderList(form);
      done();
    },
    /**
     * 刷新回调
     */
    refreshChange(info) {
      this.getOrderList(this.page, this.filterForm(info.searchForm));
    },
    // 带参数传到下一个页面
    handlerSale(row) {
      let query = {
        shipRecordSn: row.supplySn
      };
      this.$router.push({ path: "/shipRecord/completeShip", query: query });
    },
    // 采购订单编号
    purchaseSerial(row) {
      let query = {
        res: {
          buyOrderSn: row.buyOrderSns
        }
      };
      this.$router.push({
        path: "/supply/purchasedeatilssupplygoods",
        query: query
      });
    },
    // 发货订单编号
    shipSerial(row) {
      let query = {
        res: {
          shipRecordSn: row.shipRecordSn
        }
      };
      this.$router.push({ path: "/shipRecord/shipDetail", query: query });
    },
    // 取消按钮
    supplyCancel() {},
    // 发货
    supplyShip(row) {
      let params = {
        supplySn: row.supplySn
      };
      //获取订单号信息
      supplyInfo(params).then(res => {
        let query = {
          res: {
            // supplySn: row.supplySn,
            shipRecordSn: res.data.data.shipRecordSn
          }
        };
        this.$router.push({ path: "/shipRecord/completeShip", query: query });
      });
    },
    // 售后
    afterSale(row) {
      let query = {
        shipRecordSn: row.supplySn
      };
      this.$router.push({ path: "/shipRecord/shipList", query: query });
    },
    orderDetails(row) {
      console.log(row);
      let query = {
        shipRecordSn: row.supplySn
      };
      console.log(query);
      this.$router.push({
        path: "/supply/orderdetailssupplygoods",
        query: query
      });
    },
    getHeight() {
      let tableHeight = Math.max(window.innerHeight - 330, 400);
      this.option.maxHeight = tableHeight + "px";
    }
  }
};
</script>

<style>
.search-wrap {
  display: flex;
  flex-wrap: wrap;
  padding: 24px 24px 0 50px;
}
.search-wrap1 {
  display: flex;
  flex-wrap: wrap;
  padding: 24px 24px 0 50px;
}
.search-wrap2 {
  display: flex;
  flex-wrap: wrap;
  padding: 24px 24px 0 50px;
}
.search-wrap .select {
  display: flex;
}
.search-wrap1 .serch {
  display: flex;
}
.search-wrap2 .supplDay {
  display: flex;
}
.table .order {
  line-height: 36px;
  text-align: center;
  display: flex;
  /* margin-left: 40px; */
  vertical-align: middle;
}
.serchBtn {
  margin-left: 40px;
}
.detailDiv {
  display: flex;
}
.detailText {
  margin: 0px 0 0 10px;
}
</style>
